<?php

namespace App\Http\Controllers\Admin;

use App\Exports\AfterSaleCompensationExport;
use App\Exports\SupplierExport;
use App\Http\Controllers\Controller;
use App\Models\Supplier;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class SupplierController extends Controller
{
    public function store(Request $request)
    {
        $supplier = null;
        try {
            $supplier = Supplier::query()->create(
                tap(
                    $request->only([
                        'name', 'contact', 'phone', 'password', 'emergency_contact', 'emergency_phone',
                        'province', 'city', 'area', 'address', 'return_province', 'return_city',
                        'return_area', 'return_address', 'business_license', 'nature', 'business_scope', 'delivery_time',
                        'settlement_method', 'collection_account', 'support_invoicing'
                    ]),
                    function (&$values) {
                        $values['password'] = Hash::make($values['password']);
                    }
                )
            );
            $supplier->update(['numbering' => 'G' . str_pad($supplier['id'], 4, 0, STR_PAD_LEFT)]);
        } catch (\Exception $e) {
            \Log::error($e);
            $this->response->errorBadRequest($e->getMessage());
        }

        return $this->response->created(null, $supplier);
    }

    public function update(Request $request, $id)
    {
        $supplier = null;

        try {
            $supplier = Supplier::query()
                ->withoutGlobalScope('status')
                ->findOrFail($id);

            $supplier->update(
                $request
                    ->only([
                        'name', 'contact', 'phone', 'password', 'emergency_contact', 'emergency_phone',
                        'province', 'city', 'area', 'address', 'return_province', 'return_city',
                        'return_area', 'return_address', 'business_license', 'nature', 'business_scope', 'delivery_time',
                        'settlement_method', 'collection_account', 'support_invoicing', 'status'
                    ])
            );
        } catch (\Exception $e) {
            $this->response->errorBadRequest($e->getMessage());
        }

        return $this->response->created(null, $supplier);
    }

    public function list(Request $request)
    {
        if ($request->has('export')) {
            return (new SupplierExport($request))->download(sprintf('供应商(%s).xls', Carbon::now()->format('YmdHisu')));
        }

        return $this->response->array(
            Supplier::query()
                ->withoutGlobalScope('status')
                ->with([
                    'province:code,name',
                    'city:code,name',
                    'area:code,name',
                ])
                ->when($request->get('name'), function (Builder $query, $name) {
                    $query->where('name', 'like', '%' . $name . '%');
                })
                ->when($request->get('province'), function (Builder $query, $province) {
                    $query->where('province', $province);
                })
                ->when($request->get('city'), function (Builder $query, $city) {
                    $query->where('city', $city);
                })
                ->when($request->get('area'), function (Builder $query, $area) {
                    $query->where('area', $area);
                })
                ->when($request->get('contact'), function (Builder $query, $contact) {
                    $query->where('contact', 'like', '%' . $contact . '%');
                })
                ->when($request->get('phone'), function (Builder $query, $phone) {
                    $query->where('phone', 'like', '%' . $phone . '%');
                })
                ->when($request->get('status'), function (Builder $query, $status) {
                    $query->where('status', $status);
                })
                ->when($request->get('created_at_begin'), function (Builder $query, $createdAtBegin) {
                    $query->where('created_at', '>=', $createdAtBegin);
                })
                ->when($request->get('created_at_end'), function (Builder $query, $createdAtEnd) {
                    $query->where('created_at', '<=', Carbon::parse($createdAtEnd)->endOfDay());
                })
                ->select(['id', 'numbering', 'name', 'province', 'city', 'area', 'contact', 'phone', 'status', 'created_at'])
                ->paginate());
    }

    public function info(Request $request, $id)
    {
        $supplier = Supplier::query()
            ->withoutGlobalScope('status')
            ->when($request->get('original', false), function (Builder $query) {
                $query->with([
                    'province:code,name',
                    'city:code,name',
                    'area:code,name',
                    'returnProvince:code,name',
                    'returnCity:code,name',
                    'returnArea:code,name'
                ]);
            })
            ->find($id);

        return $this->response->array(
            $request->get('original', false) ?
                Arr::except($supplier->getRawOriginal(), ['password']) :
                $supplier->toArray());
    }
}
